import React, { useCallback } from 'react';
import { LogoutOutlined} from '@ant-design/icons';
import { Avatar, Menu, Spin } from 'antd';
import { history, useModel } from 'umi';
import { outLogin } from '@/services/login';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';

export type GlobalHeaderRightProps = {
  menu?: boolean;
};



/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  const cookie = JSON.stringify(document.cookie.match(new RegExp("(^| )uid=([^;]*)(;|$)")));
  const cookieArr = JSON.parse(cookie);
  if(null !== cookieArr && undefined !== cookieArr){
    await outLogin({'uid': cookieArr[2]});
    if (window.location.pathname !== '/login') {
      history.replace({
        pathname: '/login',
      });
    }
  }
};


const AvatarDropdown: React.FC<GlobalHeaderRightProps> = () => {
  const { initialState} = useModel('@@initialState');

  const onMenuClick = useCallback(
    () => {
      loginOut();
        return;
    },
    [],
  );

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }
  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );
  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar size="small" className={styles.avatar} src='https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png' alt="avatar" />
        <span className={`${styles.name} anticon`}>admin</span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
